﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ProgNetComponentsDx.Options;
using DevExpress.XtraRichEdit.Forms;
using System.Diagnostics;
using DevExpress.XtraRichEdit.Commands;
using DevExpress.XtraRichEdit.API.Native;
using DevExpress.XtraRichEdit;
using DevExpress.XtraRichEdit.Model;

namespace BuildHelper.Work.Short
{
    public partial class NotesControl : UserControl
    {
        public NotesControl()
        {
            InitializeComponent();
            System.Reflection.FieldInfo fi = typeof(WordsDocumentModelIterator).GetSingleField("WordsDelimiter", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
            if (fi != null)
            {
                List<char> WordsDelimiter = fi.GetValue(null) as List<char>;
            }
        }
        public string File
        {
            get;
            set;
        }
        public NotesControl(string file)
        {
            InitializeComponent();
            this.File = file;
        }
        public void ReadDocument()
        {
            if (System.IO.File.Exists(File))
            {
                try
                {
                    richEditControl.LoadDocument(File, DevExpress.XtraRichEdit.DocumentFormat.Rtf);
                }
                catch (Exception ex)
                {
                    ex.Log();
                }
            }
        }
        public void SaveDocument()
        {
            if (isLoaded)
            {
                try
                {
                    richEditControl.SaveDocument(File, DevExpress.XtraRichEdit.DocumentFormat.Rtf);
                }
                catch (Exception ex)
                {
                    ex.Log();
                }
            }
        }

        private void richEditControl_BeforeDispose(object sender, EventArgs e)
        {
            if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Notes.ZapisujZawartosc))
            {
                SaveDocument();
            }
        }
        private bool isLoaded = false;
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            isLoaded = true;
            richEditControl_SizeChanged(null, null);
            if (OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Rozne_Group.Skroty_Group.Notes.ZapisujZawartosc))
            {
                ReadDocument();
            }
        }

        //private void bbiBookmark_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    ShowBookmarkForm();
        //}
        //BookmarkForm bookmarkForm;
        //internal virtual void ShowBookmarkForm()
        //{
        //    if (bookmarkForm == null)
        //    {
        //        BookmarkFormControllerParameters p = new BookmarkFormControllerParameters();

        //        bookmarkForm = new BookmarkForm(p);
        //        bookmarkForm.TopMost = true;
        //        (bookmarkForm.Controls[2] as DevExpress.XtraEditors.SimpleButton).Click += new EventHandler(NotesControl_CloseClick);
        //        (bookmarkForm.Controls[4] as DevExpress.XtraEditors.SimpleButton).Click += new EventHandler(NotesControl_AddClick);
        //        (bookmarkForm.Controls[6] as DevExpress.XtraEditors.SimpleButton).Click += new EventHandler(NotesControl_DeleteClick);
        //        bookmarkForm.FormClosed += new FormClosedEventHandler(bookmarkForm_FormClosed);
        //        bookmarkForm.LookAndFeel.ParentLookAndFeel = richEditControl.LookAndFeel;
        //        bookmarkForm.Show((IWin32Window)ShortForm.Instance);
        //    }
        //    else
        //    {
        //        bookmarkForm.BringToFront();
        //        System.User32.SwitchToThisWindow(bookmarkForm.Handle, false);
        //    }
        //}

        void NotesControl_CloseClick(object sender, EventArgs e)
        {
            //bookmarkForm.Close();
        }
        void NotesControl_AddClick(object sender, EventArgs e)
        {
           // bookmarkForm.RunMethod("UpdateForm");
        }
        void NotesControl_DeleteClick(object sender, EventArgs e)
        {
            //bookmarkForm.RunMethod("UpdateForm");
        }
        void bookmarkForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //bookmarkForm.Dispose();
           // bookmarkForm = null;
        }

        private void richEditControl_SizeChanged(object sender, EventArgs e)
        {
            Size s = paragraphBar1.Size;
            if (splitContainerControl1.SplitterPosition == 0 && !splitContainerControl1.Collapsed)
            {
                splitContainerControl1.Collapsed = true;
                splitContainerControl1.SplitterPosition = s.Height;
                return;
            }
            splitContainerControl1.SuspendLayout();
            if (s.Height > 0)
            {
                splitContainerControl1.Panel1.MaximumSize = new Size(0, s.Height);
                splitContainerControl1.Panel1.MinimumSize = new Size(0, s.Height);
            }
            splitContainerControl1.SplitterPosition = s.Height;
            splitContainerControl1.ResumeLayout(false);
        }

        private void bbiSoftDev_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string sel = richEditControl.Document.GetText(richEditControl.Document.Selection).AsString().Trim();
            if (sel.IsNull())
            {
                RichEditSelectionCommand prev = new PreviousWordCommand(richEditControl);
                RichEditSelectionCommand next = new NextWordCommand(richEditControl);

                int start = richEditControl.Document.CaretPosition.ToInt();
                DocumentRange range;
                int idx;
                int tmp = start;
                int end = 0;
                while (true)
                {
                    try
                    {
                        range = richEditControl.Document.CreateRange(start - 1, 1);
                        sel = richEditControl.Document.GetText(range);
                        if (sel.IsNullOrWhiteSpace())
                            break;
                    }
                    catch { }
                    prev.Execute();
                    idx = richEditControl.Document.CaretPosition.ToInt();
                    if (idx == start)
                        break;
                    start = idx;
                    if (start == 0)
                        break;

                    range = richEditControl.Document.CreateRange(start - 1, 1);
                    sel = richEditControl.Document.GetText(range);
                    if (sel.IsNullOrWhiteSpace())
                        break;
                }
                while (true)
                {
                    try
                    {
                        next.Execute();
                        idx = richEditControl.Document.CaretPosition.ToInt();

                        if (idx == end)
                        {
                            range = richEditControl.Document.CreateRange(start, idx - start);
                            sel = richEditControl.Document.GetText(range).AsString().Trim();
                            break;
                        }
                        range = richEditControl.Document.CreateRange(idx - 1, 1);
                        sel = richEditControl.Document.GetText(range).AsString().Trim();
                        if (sel.IsNullOrWhiteSpace())
                        {
                            range = richEditControl.Document.CreateRange(start, idx - start);
                            sel = richEditControl.Document.GetText(range).AsString().Trim();
                            break;
                        }
                    }
                    catch
                    {
                        break;
                    }

                    end = idx;
                }
                richEditControl.Document.Selection = richEditControl.Document.CreateRange(tmp, 0);
            }
            sel = sel.AsString().XReplace("[^A-Za-z0-9\\-]+", "").Trim();

            if (sel.XMatch("^\\w+-\\w+-\\d+\\w*$"))
            {
                GlobalTools.SoftDevTools.NawigateTo(sel);
            }
        }

    }


}
